<template>
  <div class="chat-container">
    <div class="chat-header">
      <h2>智能对话助手</h2>
    </div>
    <div class="messages-container" ref="chatContainer">
      <div
        v-for="(message, index) in messages"
        :key="index"
        class="message-wrapper"
        :class="{
          'user-message-wrapper': message.role === Role.USER,
          'ai-message-wrapper': message.role === Role.SYSTEM || message.role === Role.ASSISTANT,
        }"
      >
        <div class="avatar-container" v-if="message.role === Role.SYSTEM || message.role === Role.ASSISTANT">
          <div class="avatar">AI</div>
        </div>
        <div
          class="message"
          :class="{
            'user-message': message.role === Role.USER,
            'ai-message': message.role === Role.SYSTEM || message.role === Role.ASSISTANT,
          }"
        >
          <MdComponent :markdown-text="message.content!" />
        </div>
        <div class="avatar-container" v-if="message.role === Role.USER">
          <div class="avatar user-avatar">您</div>
        </div>
      </div>
    </div>
    <div class="input-container">
      <n-input
        v-model:value="newMessage"
        @keyup.shift.enter="sendMessage"
        placeholder="输入您的问题..."
        class="chat-input"
        :disabled="loading"
      />
      <n-button
        type="primary"
        @click="sendMessage"
        class="send-button"
        :loading="loading"
        :disabled="loading || newMessage.trim() === ''"
      >
        <template v-if="!loading">发送</template>
        <template v-else>处理中...</template>
      </n-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { nextTick, ref, onBeforeUnmount } from 'vue'
import { type AIMessage, Role } from '@/types/entity/AIMessage'
import { fetchEventSource } from "@microsoft/fetch-event-source";
import { useMessage } from 'naive-ui'
import MdComponent from '@/components/MdComponent.vue'

const chatContainer = ref<HTMLElement | null>(null)

const messages = ref<AIMessage[]>([
  {
    role: Role.SYSTEM,
    content: '您好，我是您的智能助手，有什么可以帮助您的吗？'
  },
])

const message = useMessage()

const newMessage = ref('')

const loading = ref(false)
const eventSource = ref<EventSource | null>(null);
const userStore = useUserStore()

const getResponse = async (params: AIMessage[]) => {
  try {
    loading.value = true

    // 添加 AI 消息
    messages.value.push({
      role: Role.ASSISTANT,
      content: ""
    })
    const currentIndex = messages.value.length - 1

    const controller = new AbortController()
    await fetchEventSource('/api/v1/ai/answer', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': userStore.token,
      },
      body: JSON.stringify(params),
      signal: controller.signal,
      onmessage: (msg) => {
        if (msg.data === '[DONE]') {
          console.log(messages.value[currentIndex].content)
          loading.value = false
          return
        }
        console.log(msg.data)
        // 将\\x0A替换为换行符
        msg.data = msg.data.replace(/\\x0A/g, '\n')
        // 如果在###后面，#后面加一个空格
        msg.data = msg.data.replace(/#(?!#)/g, '# ')
        messages.value[currentIndex].content += msg.data
        scrollToBottom()
      },
      onclose: () => {
        loading.value = false
      },
      onerror: (err) => {
        loading.value = false
        message.error('请求失败')
        console.error(err)
        throw err
      },
      openWhenHidden: true,
    })
    onBeforeUnmount(() => controller.abort())
  } catch(e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

const sendMessage = async () => {
  if (newMessage.value.trim() !== '' && !loading.value) {
    messages.value.push({ role: Role.USER, content: newMessage.value.trim() })
    newMessage.value = ''
    await nextTick()
    scrollToBottom()
    await getResponse(messages.value)
  }
}

const scrollToBottom = () => {
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight
  }
}

onBeforeUnmount(() => {
  if (eventSource.value) {
    eventSource.value.close();
    eventSource.value = null;
  }
})
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 0;
  margin: 0 auto;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.chat-header {
  background: #f5f9f7;
  color: #2c3e50;
  padding: 20px 30px;
  text-align: center;
  border-bottom: 1px solid #e8f5e9;
}

.chat-header h2 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 500;
  letter-spacing: 1px;
  color: #1b5e20;
}

.messages-container {
  flex-grow: 1;
  overflow-y: auto;
  padding: 30px;
  background: #ffffff;
  scrollbar-width: thin;
  scrollbar-color: #e8f5e9 transparent;
}

.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track {
  background: transparent;
}

.messages-container::-webkit-scrollbar-thumb {
  background-color: #e8f5e9;
  border-radius: 20px;
}

.message-wrapper {
  display: flex;
  width: 100%;
  margin-bottom: 28px;
  align-items: flex-start;
}

.user-message-wrapper {
  justify-content: flex-end;
}

.ai-message-wrapper {
  justify-content: flex-start;
}

.avatar-container {
  width: 38px;
  height: 38px;
  flex-shrink: 0;
  margin: 0 12px;
}

.avatar {
  width: 38px;
  height: 38px;
  border-radius: 50%;
  background: #e8f5e9;
  color: #2e7d32;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 500;
  font-size: 14px;
  box-shadow: 0 2px 6px rgba(46, 125, 50, 0.1);
}

.user-avatar {
  background: #f1f8e9;
  color: #33691e;
  box-shadow: 0 2px 6px rgba(51, 105, 30, 0.1);
}

.message {
  padding: 16px 20px;
  border-radius: 12px;
  max-width: calc(100% - 120px);
  word-break: break-word;
  font-size: 16px;
  line-height: 1.6;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.user-message {
  background-color: #e8f5e9;
  color: #1b5e20;
  border: 1px solid rgba(46, 125, 50, 0.1);
}

.ai-message {
  background-color: #ffffff;
  color: #2c3e50;
  border: 1px solid #f1f1f1;
}

.input-container {
  display: flex;
  gap: 12px;
  padding: 20px 30px;
  background-color: #f5f9f7;
  border-top: 1px solid #e8f5e9;
}

.chat-input {
  flex-grow: 1;
  border-radius: 6px;
  font-size: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  border: 1px solid #e8f5e9;
}

.chat-input:focus {
  box-shadow: 0 0 0 2px rgba(46, 125, 50, 0.1);
  border-color: #81c784;
}

.send-button {
  padding: 0 24px;
  height: 40px;
  background: #4caf50;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(76, 175, 80, 0.2);
}

.send-button:hover:not(:disabled) {
  background: #43a047;
  box-shadow: 0 3px 6px rgba(76, 175, 80, 0.3);
}

.send-button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .message {
    max-width: calc(100% - 80px);
  }

  .chat-header {
    padding: 16px 20px;
  }

  .chat-header h2 {
    font-size: 1.25rem;
  }

  .messages-container {
    padding: 20px;
  }

  .input-container {
    padding: 15px 20px;
  }
}
</style>

